(ns ura.Org
  (:require
   [reagent.core :as r]
   [reagent.dom :as rd]
   [stylefy.core :as sty]
   [stylefy.reagent :as stylefy-reagent]
   [ajax.core :refer [GET POST DELETE PUT]]
   [ura.common :as uc :refer [log spy]]
   [ura.config :refer [getUrl]]
   [ura.notify :refer [showNotify]]
   [ura.ui :as ui]
   [ura.style :refer [attr]]
   [ura.table :refer [MyTable]]

   [re-com.core :as rc :refer [at]]
   ))

(def tableData (r/atom {:data []}))
(def dataItem (r/atom {}))
(def modal1 (r/atom false))

(def alert (r/atom false))

(def orgList (r/atom []))

(defn loadOrgList []
  (GET (getUrl "/ura/org")
       {
        :response-format :json
        :keywords? true
        :handler
        (fn [resp]
          (log "get org list " resp)
          (reset! orgList resp)
          )
        }
       )
  )

(defn loadData [& param]
  (log "query org data " param)
  (GET (getUrl "/ura/org")
       {:params (js->clj param)
        :response-format :json
        :keywords? true
        :handler
        (fn [resp]
          (log "get org resp " resp)
          (swap! tableData assoc :data resp)
          )
        })
  )

(defn saveItem [data]
  (let [method (if (nil? data.id) POST PUT)]
    (log "save org data " method data)
    (method (getUrl "/ura/org")
            {
             :headers {:content-type "application/json"}
             :body (js/JSON.stringify (clj->js data))
             :handler (fn [resp]
                        (log " orgInfo " resp)
                        )
             :error-handler (fn [resp]
                              (log "error " resp)
                              (showNotify (str "get error" resp))
                              )
             :finally (fn []
                        (reset! modal1 false)
                        (loadData)
                        )
             })
    )
  )

(defn addItem [data]
  (log "save org " @dataItem)
  )

(defn callDelete [data]
  (DELETE (getUrl (str "/ura/org/" (:id data)))
          {:handler (fn [resp]
                      (loadData)
                      (log "delete data" resp)
                      )
           }))


;;; ui
(def formRef (r/atom {}))

(defn handleEdit [row rowData index]
  (let [r (js->clj row :keywordize-keys true)
        d (js->clj rowData :keywordize-keys true)
        i index]
    (log "edit row" r)
    (reset! dataItem r)
    )
  (log "get dataitem " @dataItem)
  (reset! modal1 true)
  )


(defn handleNew []
  (reset! dataItem {})
  (log "reset dataitem : " @dataItem)
  (reset! modal1 true)
  )


(defn confirmForm [dataItem]
  (log "validate form data and save it: " dataItem)
  (saveItem dataItem)
  ;; (let [a @formRef]
  ;;   (-> (a.validateFields)
  ;;       (.then #(saveItem %))
  ;;       (.catch #(log %))
  ;;       (.finally #(log %))
  ;;       )
  ;;   )
  )


(defn editModel []
  (fn []
    (when @modal1
      [rc/modal-panel {:src (rc/at)
                       :backdrop-on-click #(reset! modal1 nil)
                       :child [:div
                               [:span.is-size-5.has-text-weight-bold "添加组织"]
                               [:div {}
                                [ui/MyFormField {:label "名称" :required true}
                                 [ui/MyInput {:type "text" :placeholder "请输入名称"
                                              :style {:width "100%"}
                                              :model (r/cursor dataItem [:name])
                                              }]]
                                
                                [ui/MyFormField {:label "编码" :required true}
                                 [ui/MyInput {:type "text" :placeholder "请输入编码"
                                              :style {:width "100%"}
                                              :model (r/cursor dataItem [:code])
                                              }]]

                                [ui/MyFormField {:label "上级组织"}
                                 [rc/single-dropdown {:model (r/cursor dataItem [:parent_id])
                                                      :choices orgList
                                                      :label-fn :name
                                                      :width "250px"
                                                      :on-change #(swap! dataItem assoc :parent_id %)
                                                      :attr {:key "asdf"}
                                                      }]]

                                [ui/MyFormField {:label "电话"}
                                 [ui/MyInput {:type "text" :placeholder "请输入电话"
                                              :style {:width "100%"}
                                              :model (r/cursor dataItem [:infos :tel])
                                              }]]
                                
                                [ui/MyFormField {:label "说明"}
                                 [ui/MyInput {:type "text" :placeholder "请输入说明"
                                              :style {:width "100%"}
                                              :model (r/cursor dataItem [:description])
                                              }]]
                                [:div (attr :flex :jc-e :gap=15)
                                 [:button.btn {:on-click #(reset! modal1 false)} "取消"]
                                 [:button.btn.btn-primary {:on-click #(confirmForm @dataItem)} "确定"]
                                 ]
                                ]
                               ]
                       }])))


;; Top tool bar
(defn searchForm []
  (let [searchParam (r/atom {})]
    (fn []
      [:div (attr :flex :gap=6)
       [ui/my-label "名称："]
       [ui/MyInput {:model (r/cursor searchParam [:name])}]
       [ui/my-label "上级组织："]
       [rc/single-dropdown {:model (r/cursor searchParam [:parent_id])
                            :choices orgList
                            :label-fn :name
                            :width "300px"
                            :on-change #(swap! searchParam assoc :parent_id %)
                            }

        ]
       [:button.btn.btn-primary {:on-click #(loadData @searchParam)}
        [:i.fa.fa-search.mr-2] "查询"]
       [:button.btn.btn-primary {:on-click #(do (reset! searchParam {}) (loadData))}
        [:i.fa.fa-rotate-right.mr-2] [:span "重置"]]
       ]
      )
    )
  )


(defn topBar []
  [ui/my-toolbar {}
   [rc/button {:src (rc/at)
               :label "添加组织"
               :class "btn btn-primary"
               :on-click handleNew} ]
    [searchForm]
   ]
)


(defn handleSelect [keys rows]
  (log "select row: " keys rows)
  (let [selected (js->clj rows :keywordize-keys true)]
    (showNotify (str "You have selected: " (map :username selected)))
    )
  )


(defn datatable []
  [MyTable
   {:data @(r/cursor tableData [:data])
    :striped true
    :fullwidth true
    :hoverable true
    :columns [
              {:title "编号" :prop "id"}
              {:title "名称" :prop "name" :sorter #(uc/comparison %1 %2 :org_name)}
              {:title "编码" :prop "code" :sorter #(uc/comparison %1 %2 :code)}
              {:title "上级组织名称" :prop "parent_id" :sorter #(uc/comparison %1 %2 :parent_id)
               :render (fn [rowData value]
                         (let [orgs @orgList]
                           (log "parent " rowData value)
                           (:name (some #(when (= value (:id %)) %) orgs))
                           ))
               }
              {:title "电话" :prop ["infos" "tel"]}
              {:title "说明" :prop "description"}
              {:title "其他" :prop "infos"}
              {:title "操作" :width "220px"
               :render (fn [rowData value]
                         (let [delpop (r/atom false)
                               closepop #(reset! delpop false)
                               ]
                           [:div (attr :flex :gap=5)
                            [rc/popover-anchor-wrapper :src (rc/at)
                             :showing? delpop
                             :position :below-center
                             :anchor [:button.btn.btn-sm {:on-click #(reset! delpop true)} "删除" ]
                             :popover [rc/popover-content-wrapper :src (rc/at)
                                       :width "300px"
                                       :backdrop-opacity 0.3
                                       :on-cancel closepop
                                       :title "是否删除数据？ "
                                       :close-button? true
                                       :body [:div
                                              [:span {} (:name value)]
                                              [:div (attr :flex :jc-e :gap=10)
                                               [:button.btn {:on-click closepop} "取消"]
                                               [:button.btn.btn-primary {:on-click #(callDelete value)} "确定"]
                                               ]]]]
                           
                            [:button.btn.btn-sm
                             {:on-click #(handleEdit rowData rowData 0) } "编辑"]
                            ]
                           )
                         )
               }]
    :page {:current 1 :pageSize 10 :pageSizeItem [10, 20, 50, 100]}
    }]
  ;; (sty/class "wfull" {:width "100%"})
  ;; [:div (attr :width=100%)
   
  ;;  [rc/v-table {:src (at)
  ;;                      :model (r/cursor tableData [:data])
  ;;                      :columns [
  ;;                                {:id :id :header-label "编号" :row-label-fn :id :width 100}
  ;;                                {:id :name :header-label "名称" :row-label-fn :name :width 200}
  ;;                                {:id :code :header-label "编码" :row-label-fn :code :width 200}
  ;;                                {:id :description :header-label "描述" :row-label-fn :description  }
  ;;                                ]
  ;;                      :row-footer-renderer (fn [i r] i)
  ;;                      :max-width "100%"
  ;;                      :parts {:middle-section {:style {:width "100%" :max-width nil}}}
                       
  ;;                      :class "wfull"
  ;;                      }]
  ;;]
  )

(defn genPage []
  (loadOrgList)
  (loadData)
  [:div
   [editModel]
   [topBar]
   [datatable]
   ]
)
